package com.yunduo.common;

import com.yunduo.common.RetunData.statuscode.ResultStatus;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.RetunData.statuscode.impl.UserCode;
import com.yunduo.common.YunDuoConst.FileType;
import com.yunduo.entity.PFile;
import com.yunduo.entity.vo.FileObj;
import com.yunduo.handler.exceptionhandler.OperationException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 项目公共方法
 */
@Component
public class YunDuoUtils {
    //登录认证
    public static ResultStatus login(AuthenticationToken authToken){
        //获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //登录认证
        try {
            subject.login(authToken);
        } catch (UnknownAccountException e){
            return UserCode.USER_ACCOUNT_ISNOT;
        } catch (IncorrectCredentialsException e) {
            return UserCode.USER_LOGING_PASSWORD_ERROR;
        } catch (AuthenticationException e){
            return ResultCode.ERROR;
        }
        return UserCode.USER_LOGIN_SUCCESS;
    }

    //获取系统可运行内存
    public static HashMap<String,Integer>  getSystemInfo(){
        HashMap<String, Integer> systemInfo = new HashMap<>();
        MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
       systemInfo.put("useMemory", bytesToMB(heapMemoryUsage.getUsed()));
        systemInfo.put("maxMemory",bytesToMB(heapMemoryUsage.getMax()));
        return systemInfo;
    }

    //系统中断
    public static void exit(){
        System.exit(1);
    }

    //计算内存大小
    protected static Integer bytesToMB(long bytes) {
        return Integer.valueOf(((int)(bytes / 1024 / 1024)));
    }

    //检查文件类型
    public static FileType checkFileType(String name){
        //文本文件正则
        String txtRegex = ".*\\.(txt|doc|docx|pdf|odt|rtf)$";
        String videoRegex = ".*\\.(mp4|mov|avi|mkv|wmv|flv)$";
        String imgRegex = ".*\\.(jpg|jpeg|png|gif|bmp|svg)$";
        String musicRegex = ".*\\\\.(mp3|wav|flac|aac|ogg)$";
        if(name.matches(txtRegex)){
            return FileType.TXT;
        }
        if(name.matches(videoRegex)){
            return FileType.VIDEO;
        }
        if(name.matches(imgRegex)){
            return FileType.IMAGE;
        }
        if(name.matches(musicRegex)){
            return FileType.MUSIC;
        }
        return FileType.OTHER;

    }

    //获取当前请求的Request
    public static HttpServletRequest getRequest() throws NullPointerException{
        //获取request
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    //切割日期字符串 - 返回日期
    public static LocalDateTime splitDateString(String date){
        if(StringUtils.isEmpty(date)){
            throw new OperationException(ResultCode.ERROR.getCode(),"格式错误");
        }
        try{
            String[] split = date.split("-");
            return LocalDateTime.of(Integer.valueOf(split[0]),Integer.valueOf(split[1]),Integer.valueOf(split[2]),0,0);
        } catch (Exception e){
            throw new OperationException(ResultCode.ERROR.getCode(),"格式错误");
        }
    }

    //根据PFile对象返回FileObj
    public static FileObj getFileObjForPFile(PFile pFile){
        return new FileObj(pFile.getId(),checkFileType(pFile.getName()),pFile.getName(),null);
    }


    //手机号加密
    public static String phoneEncode(String phone){
        int length = phone.length();
        int cut = (length/3)-1;
        String begin = phone.substring(0, cut);
        String end = phone.substring(length - cut - 1, length - 1);
        StringBuffer buffer = new StringBuffer();
        buffer.append(begin);
        for(int i = cut; i >= 0; i--){
            buffer.append('*');
        }
        buffer.append(end);
        return buffer.toString();
    }

    //切割Ids
    public static ArrayList<String> OrderIdsSplit(String ids){
        String[] idsInfo = ids.split(",");
        ArrayList<String> endIds = new ArrayList<>();
        for (int i = 0; i < idsInfo.length; i++) {
            String[] idData = idsInfo[i].split("\\*");
            endIds.add(idData[0]);
        }
        return endIds;
    }
}
